package org.example.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    
    private static final String KEY = "ithy";
    
    //接收业务数据，生成token并返回
    public static String genToken(Map<String, Object> claims){
        return JWT.create()
                .withClaim("claims", claims)
                .withExpiresAt(new Date(System.currentTimeMillis()+1000*60*60*12))
                .sign(Algorithm.HMAC256("ithy"));
    }
    
    //接收token，验证token，并返回业务数据
    public static Map<String, Object> parseToken(String token){
        return JWT.require(Algorithm.HMAC256(KEY))
                .build()
                .verify(token)
                .getClaim("claims")
                .asMap();
    }
    
    // 令牌验证
    public static boolean isExpired(String token){
        //验证token
        try{
            Map<String, Object> claims = JwtUtil.parseToken(token);
            //放行
            return true;
        }catch (Exception e){
            //不放行
            return false;
        }
    }
    
    public static void main(String[] args) {
//        Map<String, Object> claims = new HashMap<>();
//        claims.put("username", "admin");
//        claims.put("password", "123");
//        String s = genToken(claims);
//        System.out.println(s);
//        System.out.println("\n\n");
        String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGFpbXMiOnsibG9naW5OYW1lIjoicHBwcHAiLCJ0ZW5hbnRJZCI6OSwiaWQiOjIsInVzZXJuYW1lIjoi5bCPcCJ9LCJleHAiOjE3MzA5OTI2NTN9.3BtdaCOvnlMweQCGBgV78r0aKk1k0VZ8W6Zx278M_LY";
        
        Map<String, Object> stringObjectMap = JwtUtil.parseToken(token);
        System.out.println(stringObjectMap.toString());
    }
}
